﻿using Exceptionless.Core.Extensions;
using Exceptionless.Core.Models;
using Exceptionless.Core.Pipeline;
using Microsoft.Extensions.Logging;

namespace Exceptionless.Core.Plugins.Formatting;

[Priority(50)]
public sealed class SessionFormattingPlugin : FormattingPluginBase
{
    public SessionFormattingPlugin(AppOptions options, ILoggerFactory loggerFactory) : base(options, loggerFactory) { }

    private bool ShouldHandle(PersistentEvent ev)
    {
        return ev.IsSessionStart() || ev.IsSessionEnd() || ev.IsSessionHeartbeat();
    }

    public override SummaryData? GetStackSummaryData(Stack stack)
    {
        if (!stack.SignatureInfo.ContainsKeyWithValue("Type", Event.KnownTypes.Session, Event.KnownTypes.SessionEnd, Event.KnownTypes.SessionHeartbeat))
            return null;

        return new SummaryData { Id = stack.Id, TemplateKey = "stack-session-summary", Data = new Dictionary<string, object>() };
    }

    public override string? GetStackTitle(PersistentEvent ev)
    {
        if (!ShouldHandle(ev))
            return null;

        if (ev.IsSessionHeartbeat())
            return "Session Heartbeat";

        return ev.IsSessionStart() ? "Session Start" : "Session End";
    }

    public override SummaryData? GetEventSummaryData(PersistentEvent ev)
    {
        if (!ShouldHandle(ev))
            return null;

        var data = new Dictionary<string, object?> { { "SessionId", ev.GetSessionId() }, { "Type", ev.Type } };
        AddUserIdentitySummaryData(data, ev.GetUserIdentity());

        if (ev.IsSessionStart())
        {
            data.Add("Value", ev.Value.GetValueOrDefault());

            var endTime = ev.GetSessionEndTime();
            if (endTime.HasValue)
                data.Add("SessionEnd", endTime);
        }

        return new SummaryData { Id = ev.Id, TemplateKey = "event-session-summary", Data = data };
    }
}
